/*
Author: Surpass-HC
Source: https://gitee.com/hxchuan000/clpc-1
Mail: surpass-hc@qq.com
*/
#include <lxPipe.h>
int pipeOptFree(struct pipeOptStruct *pipOpt)
{
    if (pipOpt == NULL)
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    if (pipOpt->fd >= 0)
    {
        close(pipOpt->fd);
        pipOpt->fd = 0;
    }
    return 0;
}
int pipeOptOpen(struct pipeOptStruct *pipOpt)
{
    if (pipOpt->pipFile == NULL)
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    if (pipeOptFree(pipOpt) < 0)
    {
        return -1;
    }
    mkfifo(pipOpt->pipFile, S_IFIFO | 0666);
    pipOpt->fd = open(pipOpt->pipFile, O_RDWR);
    if (pipOpt->fd < 0)
    {
        printf("open pipe err:%s\n", pipOpt->pipFile);
        return -2;
    }
    // printf("open pipe file ok:%s, fd:%d\n", pipOpt->pipFile, pipOpt->fd);
    fileCfgNoBlock(pipOpt->fd);
    return 0;
}
int pipeOptInit(struct pipeOptStruct *pipOpt, const char *setfile, uint32_t setTmout)
{
    if (pipOpt == NULL)
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    pipOpt->pipFile = setfile;
    pipOpt->rdTmout = setTmout;
    return pipeOptOpen(pipOpt);
}
int pipeOptRead(struct pipeOptStruct *pipOpt, char *outstr, int outsize)
{
    if (!(pipOpt && pipOpt->fd >= 0))
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    return fileReadWithTime(pipOpt->fd, outstr, outsize, pipOpt->rdTmout);
}
int pipeOptWrite(struct pipeOptStruct *pipOpt, const char *optstr, int strsize)
{
    if (!(pipOpt))
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    if(!(pipOpt->fd >= 0))
    {
        printf("[%s,%d] fd error:%d\n", __FILE__, __LINE__, pipOpt->fd);
        return -1;
    }
    return write(pipOpt->fd, optstr, strsize);
}
int pipeOptWrtStr(struct pipeOptStruct *pipOpt, const char *optstr)
{
    if (!(pipOpt))
    {
        printf("[%s,%d]null pip\n", __FILE__, __LINE__);
        return -1;
    }
    if(!(pipOpt->fd >= 0))
    {
        printf("[%s,%d] fd error:%d\n", __FILE__, __LINE__, pipOpt->fd);
        return -1;
    }
    return write(pipOpt->fd, optstr, strlen(optstr));
}
